package com.lxu;

/**
 * 指令重排序带来的问题，使用volatile关键字可以避免
 */
public class VolatileDemo6 {
    private /*volatile*/ static int i, j, a, b = 0;

    public static void main(String[] args) throws InterruptedException {
        int counter = 0;
        while (true) {
            counter++;
            i = 0;
            j = 0;
            a = 0;
            b = 0;
            Thread thread1 = new Thread(() -> {
                a = 1;
                i = b;
            });

            Thread thread2 = new Thread(() -> {
                b = 1;
                j = a;
            });
            thread1.start();
            thread2.start();
            thread1.join();
            thread2.join();
            String result = "第" + counter + "次调用的结果为，(i=" + i + "j=" + j + ")";
            System.out.println(result);
            if (i == 0 && j == 0) {
                break;
            }
        }
    }
}
